package models

import (
	"dog/appconfig"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	DB  *gorm.DB
	err error
)

func Init() {
	ConfigMysql := appconfig.Appconf.Mysql
	// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/res?charset=utf8mb4&parseTime=True&loc=Local", ConfigMysql.User, ConfigMysql.Password, ConfigMysql.Host, ConfigMysql.Port)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败")
		return
	} else {
		fmt.Println("数据库连接成功")
	}

	err = DB.AutoMigrate(&Dog{}, &Mastar{}, &User{}, &Title{})
	if err != nil {
		fmt.Println("迁移失败")
	} else {
		fmt.Println("迁移成功")
	}
}
